<?php
namespace app\index\controller;
use app\index\model\Users;
use app\index\model\UsersLogs;
class Login extends \think\Controller{
    public function index(){
        $data = [];
        return view('login/index',$data);
    }
    public function check(){
        //接收从客户端提交过来的数据
        $request = \think\Request::instance();
        $data = [
            'lgnTel'    => $request->post('lgnTel'),
            'lgnPsd'    => $request->post('lgnPsd')
        ];

        //编写验证规则
        $rule = [
            'lgnTel|手机号码' =>'require',
            'lgnPsd|密码'    =>'require',
        ];

        //实例化验证器对象
        $validate = new \think\Validate($rule);
        //调用验证器的检查方法
        $result   = $validate->check($data);
        //如果输入的内容为空弹出错误信息
        if(!$result){
            $this->error($validate->getError());
        }       

        //实例化会员数据库的类
        $users = new Users();
        //验证用户名的唯一性 $row返回的是数据表中一行数据的对象
        $row = $users->where('phone',$data['lgnTel'])->find();
        if(!$row){
            return $this->error('请输入有效电话号码！');
        }
        
        //实例化用户登录日志的类
        $users_logs = new UsersLogs();
        $users_logs->users_id = $row->id;
        $users_logs->phone = $row->phone;

        //验证密码的有效性
        $is = password_verify($data['lgnPsd'],$row->password);
        if($is){
            //写入Session
            \think\Session::set('uid',$row->id);
            //密码正确，登录日志状态为1
            $users_logs->state = 1;
            $users_logs->allowField(true)->save();
            return $this->success('登录成功！','index/user.Info/index');
        }else{
            //密码错误，登录日志状态为0
            $users_logs->state = 0;
            $users_logs->allowField(true)->save();
            return $this->error('密码错误！');
        }        
        

    }


}